using B.S.NewMedical.Api.Write.Application.Command.Department;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Department
{
    /// <summary>
    /// 批量删除科室处理器
    /// 处理批量删除科室的业务逻辑，包括软删除等操作
    /// </summary>
    public class BatchDeleteDepartmentHandler : IRequestHandler<BatchDeleteDepartmentCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly ILogger<BatchDeleteDepartmentHandler> _logger;

        /// <summary>
        /// 构造函数
        /// 注入依赖的服务
        /// </summary>
        /// <param name="departmentRepository">科室仓储接口</param>
        /// <param name="logger">日志记录器</param>
        public BatchDeleteDepartmentHandler(IBaseRepository<DepartmentModel> departmentRepository, ILogger<BatchDeleteDepartmentHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除科室命令
        /// 执行批量删除科室的业务逻辑（软删除）
        /// </summary>
        /// <param name="request">批量删除科室命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果，包含删除的科室数量</returns>
        public async Task<ApiResult<int>> Handle(BatchDeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理批量删除科室命令，科室ID列表: {DepartmentIds}", 
                    string.Join(",", request.DepartmentIds));

                // 验证请求参数
                if (request.DepartmentIds == null || request.DepartmentIds.Count == 0)
                {
                    _logger.LogWarning("科室ID列表为空");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室ID列表不能为空"
                    };
                }

                // 验证所有ID是否有效
                foreach (var id in request.DepartmentIds)
                {
                    if (id <= 0)
                    {
                        _logger.LogWarning("存在无效的科室ID: {InvalidId}", id);
                        return new ApiResult<int>
                        {
                            Code = ApiEnum.Fail,
                            Msg = $"存在无效的科室ID: {id}"
                        };
                    }
                }

                // 查询所有要删除的科室
                var departmentsToDelete = _departmentRepository.GetAll()
                    .Where(d => request.DepartmentIds.Contains(d.Id) && !d.IsDeleted)
                    .ToList();

                if (!departmentsToDelete.Any())
                {
                    _logger.LogWarning("没有找到要删除的科室");
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "没有找到要删除的科室"
                    };
                }

                // 检查是否有科室存在子科室
                var departmentsWithChildren = departmentsToDelete
                    .Where(d => _departmentRepository.GetAll()
                        .Any(child => child.ParetId == d.Id && !child.IsDeleted))
                    .ToList();

                if (departmentsWithChildren.Any())
                {
                    var departmentNames = string.Join(", ", departmentsWithChildren.Select(d => d.DepartmentName));
                    _logger.LogWarning("以下科室存在子科室，无法删除: {DepartmentNames}", departmentNames);
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = $"以下科室存在子科室，请先删除子科室: {departmentNames}"
                    };
                }

                // 批量软删除科室
                int deletedCount = 0;
                foreach (var department in departmentsToDelete)
                {
                    department.IsDeleted = true;
                    await _departmentRepository.UpdateAsync(department);
                    deletedCount++;
                }

                _logger.LogInformation("批量删除科室成功，删除数量: {DeletedCount}", deletedCount);

                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = $"批量删除科室成功，共删除 {deletedCount} 个科室",
                    Data = deletedCount
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除科室时发生异常");
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = $"批量删除科室失败: {ex.Message}"
                };
            }
        }
    }
} 